/**
 * System: oshys 
 * Model: log 
 * Licence: GNU General Public License v3 
 * Author: sunwl
 * Date: 2010/02/19
 */
package org.oshys.util.logging;

import static org.oshys.util.logging.ConfigProvider.getResource;
import static org.oshys.util.logging.ConfigProvider.getBoolResource;

/**
 * Log工厂。<br>
 * 根据配置信息组装Log。
 * 
 * @author sunwl
 */
public class LogFactory {

    private LogFactory() {
    }

    public static Logger createLogger(String name) {
        Logger log = new Logger(name);
        try {
            // 获取配置的Appender名,多个Appender名使用半角逗号分割
            String[] appenders = getResource("logging.appender").split(",");
            if (appenders != null) {
                for (String appender : appenders) {
                    String appenderKey = "logging." + appender.trim() + ".appender";
                    String levelKey = "logging." + appender.trim() + ".level";
                    String asynKey = "logging." + appender.trim() + ".asynchronize";
                    // 实例化一个Appender
                    Class appenderClazz = Class.forName(getResource(appenderKey));
                    IAppender instance = (IAppender) appenderClazz.newInstance();

                    String filterLevel = getResource(levelKey);
                    IFilter filter = new LevelFilter(Level.getLevel(filterLevel));
                    // 为Appender添加一个Level过滤器
                    instance.addFilter(filter);

                    // 配置是否使用异步模式
                    if (getBoolResource(asynKey)) {
                        // System.out.println(asynKey + "---  async...");
                        // 使用异步模式
                        AsyncAppender asyncAppender = new AsyncAppender();
                        asyncAppender.addAppender(instance);
                        log.addAppender(asyncAppender);
                    } else {
                        // 使用同步模式
                        // System.out.println(asynKey + "---  sync...");
                        log.addAppender(instance);
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return log;
    }

}
